package com.strive.village.security;

import com.strive.village.entity.SysUser;
import com.strive.village.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description：通过查库实现用户信息的鉴别，同时返回用户权限信息
 * @author：StrivePeng
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        // 返回一个封装的用户详情类实体
        AccountUser accountUser = new AccountUser(user.getId(), user.getUsername(), user.getPassword(), getUserAuthority(user.getId()));
        return accountUser;
    }

    /**
     * 获取用户权限信息
     *
     * @param userId 用户id
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long userId) {
        String authority = userService.getUserAuthorityInfo(userId);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
